<?php
namespace App\Http\Controllers\FILE;

use App\Http\Controllers\V1\BaseController;
use App\Services\FILE\FilesServer;
use App\Transformers\FILE\FilesTransFormer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FilesController extends BaseController
{
    private FilesServer $serve;
    private FilesTransFormer $transform;

    private string $type='';//文件类型

    public function __construct(FilesServer $serve,FilesTransFormer $transform)
    {
        $this->serve = $serve;//服务
        $this->transform = $transform;#转换
    }
    public function getTranfsorm(): FilesTransFormer
    {
        return $this->transform;
    }
    /**
     * 按照路由返回指导响应的方法
     * @return JsonResponse|mixed|object
     */
    public function route(Request $request): mixed
    {
        try{
            $this->type = getFileTypeInfo($request->file('file')->getClientOriginalName());
        }catch (\Throwable $err){}
        return match ($request->method()) {
            'GET' => $this->list(),//获取文件数据
            "POST" => $this->add(),//添加文件数据
            "PUT" => $this->edit(),//编辑文件数据
            "DELETE" => $this->del(),//删除文件数据
            default => Fail(__('file.fail.route')),
        };

    }

    public function list():JsonResponse{//列表
        $data = $this->serve->list();
        return Success(__("file.success.list"),$data);
    }

    public function add():JsonResponse{//添加
        $data = $this->serve->add();
        if($data['status']) return Success(self::formatFileText(__('file.success.add')),$data['item']);
        return Fail(self::formatFileText(__('file.fail.add')));
    }

    public function edit():JsonResponse{//编辑
        if($this->serve->edit()) return Success(self::formatFileText(__("file.success.edit")));
        return Fail(self::formatFileText(__("file.fail.edit")));

    }

    public function del():JsonResponse{//删除
        $data = $this->serve->del();
        $this->type = $data['type'];
        if($data['status']) return Success(self::formatFileText(__("file.success.del")));
        return Fail(self::formatFileText(__("file.fail.del")));

    }


    private function formatFileText($text):string{
        return str_replace('file',$this->type,$text);
    }

}
